﻿using System;
using System.ComponentModel;
using System.ServiceModel;
using System.Xml;
using Microsoft.SqlServer.Dts.Runtime;
using SSIS.MS.xRM.xRMOrganizationServiceReference;

namespace SSIS.MS.xRM.ConnectionManager
{
    [DtsConnection(ConnectionType = "xRM 2011",
      DisplayName = "Microsoft Dynamics xRM 2011 Connection Manager",
      Description = "",
      IconResource = "",
      UITypeName = "XRMConnectionManager.XRMConnectionManagerUI,XRMConnectionManagerUI,Version=1.0.0.0,Culture=neutral,PublicKeyToken=1cb51bba29f61409")]
    public class XRMConnectionManager : ConnectionManagerBase, IDTSComponentPersist
    {
        #region Properties
        [Category("Connection Manager"), Description("Base URL")]
        public string URL { get; set; }
        [Category("Connection Manager"), Description("Organization")]
        public string Organization { get; set; }
        [Category("Connection Manager"), Description("UserName")]
        public string UserName { get; set; }
        [Category("Connection Manager"), Description("Password")]
        public string Password { get; set; }
        [Category("Connection Manager"), Description("Domain Name")]
        public string DomainName { get; set; }
        [Category("Connection Manager"), Description("Windows Integrated Authentication")]
        public bool WindowsIntegratedAuthentication { get; set; }
        #endregion

        #region variables
        OrganizationServiceClient _organizationServiceClient;
        #endregion

        #region Methods

        public override DTSExecResult Validate(IDTSInfoEvents infoEvents)
        {
            if (String.IsNullOrEmpty(UserName))
            {
                infoEvents.FireError(0, "XRMConnectionManager", "No Organization URL specified", String.Empty, 0);
                return DTSExecResult.Failure;
            }

            if (String.IsNullOrEmpty(UserName))
            {
                infoEvents.FireError(0, "XRMConnectionManager", "No Organization UserID specified", String.Empty, 0);
                return DTSExecResult.Failure;
            }

            if (String.IsNullOrEmpty(Password))
            {
                infoEvents.FireError(0, "XRMConnectionManager", "No Password specified", String.Empty, 0);
                return DTSExecResult.Failure;
            }

            if (String.IsNullOrEmpty(DomainName))
            {
                infoEvents.FireError(0, "XRMConnectionManager", "No DomainName specified", String.Empty, 0);
                return DTSExecResult.Failure;
            }

            return DTSExecResult.Success;
        }

        public override object AcquireConnection(object txn)
        {
            URL = @"http://crm2.dev.mediapostmulticanal.biz/XRMServices/2011/Organization.svc?wsdl";
            Organization = string.Empty;
            UserName = string.Empty;
            Password = string.Empty;
            DomainName = string.Empty;

            _organizationServiceClient = new OrganizationServiceClient();
            if (_organizationServiceClient.ClientCredentials != null)
                _organizationServiceClient.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(UserName, Password, DomainName);

            var endpointAdd = new EndpointAddress(new Uri(URL), EndpointIdentity.CreateDnsIdentity(""));

            _organizationServiceClient.Endpoint.Address = endpointAdd;

            return _organizationServiceClient;
        }

        public override void ReleaseConnection(object connection)
        {
            if (_organizationServiceClient != null)
            {
                if (_organizationServiceClient.State == CommunicationState.Opened)
                    _organizationServiceClient.Close();
            }
        }

        #endregion

        #region Implementation of IDTSComponentPersist

        void IDTSComponentPersist.SaveToXML(XmlDocument doc, IDTSInfoEvents infoEvents)
        {
            XmlElement taskElement = doc.CreateElement(string.Empty, "SSISxRM2011ConnectionManager", string.Empty);

            XmlAttribute url = doc.CreateAttribute(string.Empty, Keys.URL, string.Empty);
            url.Value = Organization;

            XmlAttribute organization = doc.CreateAttribute(string.Empty, Keys.OrganizationURL, string.Empty);
            organization.Value = Organization;

            XmlAttribute userId = doc.CreateAttribute(string.Empty, Keys.UserId, string.Empty);
            userId.Value = UserName;

            XmlAttribute password = doc.CreateAttribute(string.Empty, Keys.Password, string.Empty);
            password.Value = Password;

            XmlAttribute domain = doc.CreateAttribute(string.Empty, Keys.Domain, string.Empty);
            domain.Value = DomainName;

            XmlAttribute windowsIntegratedAuthentication = doc.CreateAttribute(string.Empty, Keys.Domain, string.Empty);
            windowsIntegratedAuthentication.Value = WindowsIntegratedAuthentication.ToString();

            taskElement.Attributes.Append(organization);
            taskElement.Attributes.Append(userId);
            taskElement.Attributes.Append(password);
            taskElement.Attributes.Append(domain);
            taskElement.Attributes.Append(windowsIntegratedAuthentication);

            doc.AppendChild(taskElement);
        }

        void IDTSComponentPersist.LoadFromXML(XmlElement node, IDTSInfoEvents infoEvents)
        {
            if (node.Name != "SSISxRM2011ConnectionManager")
            {
                throw new Exception("Unexpected task element when loading task.");
            }

            try
            {
                URL = node.Attributes.GetNamedItem(Keys.URL).Value;
                Organization = node.Attributes.GetNamedItem(Keys.Organization).Value;
                UserName = node.Attributes.GetNamedItem(Keys.UserId).Value;
                Password = node.Attributes.GetNamedItem(Keys.Password).Value;
                DomainName = node.Attributes.GetNamedItem(Keys.Domain).Value;
                WindowsIntegratedAuthentication = Convert.ToBoolean(node.Attributes.GetNamedItem(Keys.WindowsIntegratedAuthentication).Value);
            }
            catch
            {

            }
        }

        #endregion
    }
}
